package com.ssl.commonutils;

import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 描述：执行命令行工具类
 *
 * @author ssl
 * @create 2017/12/12 11:05
 */
public class CommandUtils {
    static Pattern p = Pattern.compile("error=(\\d+),");

    public CommandUtils() {
    }

    public static CommandResult execute(String... args) {
        CommandResult commandResult = new CommandResult();
        StringBuffer cmd = new StringBuffer();
        for (int i = 0; i < args.length; ++i) {
            if (i == 0) {
                cmd.append(args[i]);
            } else {
                cmd.append(" ").append(args[i]);
            }
        }
        commandResult.setCommand(cmd.toString());
        Process process = null;
        try {
            process = (new ProcessBuilder(args)).start();
        } catch (IOException var8) {
            Matcher m = p.matcher(var8.getMessage());
            if (m.find()) {
                commandResult.setRet(Integer.valueOf(m.group(1)).intValue());
                commandResult.setIOException(var8);
            } else {
                commandResult.setRet(-1);
                commandResult.setIOException(var8);
            }

            return commandResult;
        }

        try {
            commandResult.setOutLines(IOUtils.readLines(process.getInputStream()));
            commandResult.setErrLines(IOUtils.readLines(process.getErrorStream()));
            return commandResult;
        } catch (IOException var7) {
            commandResult.setRet(-1);
            commandResult.setIOException(var7);
            return commandResult;
        }
    }
}
